﻿using NewRen.Models.ViewModel;
using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using NewRen.Schemas;
using System.Web.Hosting;
using System.IO;
using NewRen.Models.DataModel;
using NewRen.Helpers;
using PagedList;
using NewRen.Log4net;

namespace NewRen.Controllers
{
    public class BusinessController : BaseController
    {

        public ActionResult Index(string city, string industry, int page = 1)
        {
            IEnumerable<Business> query = db.Businesses.AsEnumerable();
            List<vBusiness> businesses = new List<vBusiness>();
            if (!string.IsNullOrEmpty(city))
            {
                query = query.Where(b => b.City == city);
            }
            if (!string.IsNullOrEmpty(industry))
            {
                query = query.Where(b => b.Industry == industry);
            }
            query = query.OrderByDescending(b => b.Priority);
            int totalCount = 0;
            PagerHelper.DoPage(ref query, page, 20, ref totalCount);
            foreach (var item in query)
            {
                businesses.Add(new vBusiness(item));
            }
            var businessAsIPagedList = new StaticPagedList<vBusiness>(businesses, page, 20, totalCount);

            List<City> Cities = new List<City>();
            List<Industry> Industries = new List<Industry>();
            List<City> CitiesMore = new List<City>();
            List<Industry> INdustriesMore = new List<Industry>();

            Cities = db.Cities.DistinctBy(c => c.CityName).Take(20).ToList();
            CitiesMore = db.Cities.DistinctBy(c => c.CityName).Skip(20).ToList();
            Industries = db.Industries.DistinctBy(i => i.IndustryName).Take(15).ToList();
            INdustriesMore = db.Industries.DistinctBy(i => i.IndustryName).Skip(15).ToList();

            ViewBag.Cities = Cities;
            ViewBag.CitiesMore = CitiesMore;
            ViewBag.Industries = Industries;
            ViewBag.IndustriesMore = INdustriesMore;
            ViewBag.City = (city == null ? "" : city);
            ViewBag.Industry = (industry == null ? "" : industry);
            return View(businessAsIPagedList);
        }

        #region 商户展示页面
        /// <summary>
        /// 商户展示页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult BusinessShow(int id)
        {

            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    business.PV = business.PV + 1;
                    business.TodayPV = business.TodayPV + 1;
                    db.SaveChanges();
                    vBusiness vbusiness = new vBusiness(business);
                    ViewBag.Business = vbusiness;
                    var u = "";
                    if (vbusiness.BusinessName == null)
                    {
                        u = vbusiness.LoginName;
                    }
                    else
                    {
                        u = vbusiness.BusinessName;
                    }
                    if (CurrentUser != null)
                    {
                        BrowseRecord browserecord = new BrowseRecord();
                        string url = Request.Url.ToString();
                        browserecord = db.BrowseRecords.Where(br => br.URL == url && br.UserID == CurrentUser.ID).FirstOrDefault();
                        if (browserecord == null)
                        {
                            BrowseRecord addbrowserecord = new BrowseRecord();
                            addbrowserecord.UserID = CurrentUser.ID;
                            addbrowserecord.URL = url;
                            addbrowserecord.Title = "商户展示——" + u;
                            addbrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(addbrowserecord);
                            db.SaveChanges();
                        }
                        else
                        {
                            db.BrowseRecords.Remove(browserecord);
                            BrowseRecord updatebrowserecord = new BrowseRecord();
                            updatebrowserecord.UserID = CurrentUser.ID;
                            updatebrowserecord.URL = url;
                            updatebrowserecord.Title = "商户展示——" + u;
                            updatebrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(updatebrowserecord);
                            db.SaveChanges();

                        }
                    }
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商户展示页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Shared/Info?msg=数据异常，请稍后重试");
                }
            }
            else
            {
                return Redirect("/Business/BusinessShow/"+id);
            }

        }
        #endregion

        #region 商家宣传图片
        /// <summary>
        /// 展示商家宣传图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ShowBusinessPicture(int id)
        {
            AjaxModel ajaxmodel = new AjaxModel();
            try
            {
                List<Images> business_img = db.Images.Where(c => c.TID == id).Where(c => c.ImageType == ImageType.Business).ToList();
                if (business_img != null)
                {
                    ajaxmodel.Statu = "ok";
                    ajaxmodel.Data = business_img;
                }
                else
                {
                    ajaxmodel.Statu = "err";
                    ajaxmodel.Msg = "暂无宣传图片";
                }
            }
            catch (Exception ex)
            {
                ajaxmodel.Statu = "err";
                ajaxmodel.Msg = "数据异常";
                log.Error(new LogContent("商家宣传图片加载出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxmodel);
        }
        #endregion

        #region 商户信息展示
        /// <summary>
        /// 商户信息展示页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult Show(int id)
        {
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Business = new vBusiness(business);
                    ViewBag.Images = db.Images.Where(c => c.TID == id).Where(c => c.ImageType == ImageType.Business).ToList();
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商户展示页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/Show/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 商户信息修改
        /// <summary>
        /// 商户信息修改页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult Edit(int id)
        {
            Business bussiness = db.Businesses.Find(id);
            if (bussiness != null)
            {
                try
                {
                    ViewBag.Business = business;
                    ViewBag.Cities = db.Cities.ToList();
                    ViewBag.Industry = db.Industries.ToList();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商户信息修改页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/Edit/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
            return View();
        }
        /// <summary>
        /// 商户信息修改操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowBusiness]
        public ActionResult Edit(Business model, int id)
        {
            AjaxModel ajamodel = new AjaxModel();
            if (ModelState.IsValid)
            {
                try
                {
                    Business business = db.Businesses.Find(model.ID);
                    ViewBag.Business = business;
                    business.BusinessName = model.BusinessName;
                    business.Description = model.Description;
                    business.Phone = model.Phone;
                    business.Address = model.Address;
                    business.WhatApp = model.WhatApp;
                    business.Email = model.Email;
                    business.City = model.City;
                    business.Weibo = model.Weibo;
                    business.Industry = model.Industry;
                    db.SaveChanges();
                    ajamodel.Statu = "ok";
                    ajamodel.Msg = "修改成功";
                }
                catch (Exception ex)
                {
                    ajamodel.Statu = "err";
                    ajamodel.Msg = "修改失败，请审核一下填写的信息";
                    log.Error(new LogContent("商户信息修改出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajamodel.Statu = "err";
                ajamodel.Msg = "修改失败，请审核一下填写的信息";
            }
            return Json(ajamodel);
        }
        #endregion

        #region 修改商户密码
        /// <summary>
        /// 修改商户密码界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult PwdEdit(int id)
        {
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Business = new vPwdEdit(business);
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改商户密码页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/PwdEdit/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }

        /// <summary>
        /// 修改商户密码信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowBusiness]
        public ActionResult PwdEdit(vPwdEdit model, int id)
        {
            Business business = db.Businesses.Find(model.ID);
            if (!string.IsNullOrEmpty(model.Password))
            {
                string Password = Helpers.Encryt.GetMD5(model.Password);
                if (!business.LoginPassword.Equals(Password))
                {
                    ModelState.AddModelError("", "您输入原始密码错误！");
                }
                else
                {
                    try
                    {
                        business.LoginPassword = Helpers.Encryt.GetMD5(model.PasswordNew);
                        db.SaveChanges();
                        return RedirectToAction("Show/" + model.ID);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("修改商户密码页面出错", HttpHelper.GetIPAddress()), ex);
                        ModelState.AddModelError("", "您输入密码信息有误！");
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "您输入密码不能为空！");
            }
            ViewBag.Business = new vPwdEdit(db.Businesses.Find(business.ID));
            return View();
        }

        #endregion

        #region 修改图像
        /// <summary>
        /// 显示图像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowBusiness]
        public ActionResult PictureEdit(int id)
        {
            Business business = new Business();
            business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Business = business;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改商户密码出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/PictureEdit/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }
        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowBusiness]
        public ActionResult PictureEdit(vEdit model, int id, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                Business business = db.Businesses.Find(model.ID);
                try
                {
                    if (file != null)
                    {
                        System.IO.Stream stream = file.InputStream;
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, (int)stream.Length);
                        stream.Close();
                        model.Picture = buffer;
                        business.Picture = model.Picture;
                    }
                    else
                    {
                        business.Picture = model.Picture;
                    }
                    db.SaveChanges();
                    return RedirectToAction("Show/" + model.ID);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改商户图片出错", HttpHelper.GetIPAddress()), ex);
                    ModelState.AddModelError("", "图片信息有误，请重新上传");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息异常，请刷新页面重新上传");
            }
            ViewBag.Business = db.Businesses.Find(model.ID);
            return View();
        }
        #endregion

        #region 显示头像
        /// <summary>
        /// 显示商家头像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ShowPicture(int id)
        {
            Business business = new Business();
            business = db.Businesses.Find(id);
            if (business.Picture != null)
            {
                return File(business.Picture, "image/jpg");
            }
            else
            {
                return File("/Images/userphoto.png", "image/jpg");
            }
        }
        #endregion

        #region 商户宣传图片管理
        /// <summary>
        /// 商户宣传图片界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult BusinessPictureShow(int id)
        {
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Business = business;
                    ViewBag.Images = db.Images.Where(c => c.TID == id).Where(c => c.ImageType == ImageType.Business).ToList(); ;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商户宣传图片界面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/BusinessPictureShow/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }

        /// <summary>
        /// 商户宣传图片增加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Schemas.AccessShowBusiness]
        public ActionResult AddBusinessPicture(Business model, HttpPostedFileBase file)
        {
            Business business = db.Businesses.Find(model.ID);
            if (business != null)
            {
                if (file != null)
                {
                    try
                    {
                        string random = DateHelper.GetTimeStamp();
                        Images product_img = new Images();
                        product_img.TID = model.ID;
                        product_img.ImageType = ImageType.Business;
                        product_img.ContentType = file.ContentType;
                        product_img.Time = DateTime.Now;
                        string root = "~/BusinessFile/" + business.BusinessName + "/";
                        var phicyPath = HostingEnvironment.MapPath(root);
                        Directory.CreateDirectory(phicyPath);
                        file.SaveAs(phicyPath + random + file.FileName);
                        product_img.Path = "/BusinessFile/" + business.BusinessName + "/" + random + file.FileName;
                        db.Images.Add(product_img);
                        db.SaveChanges();
                        return Redirect("/Business/BusinessPictureShow/" + business.ID);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("商户宣传图片增加出错", HttpHelper.GetIPAddress()), ex);
                        return Redirect("/Business/AddBusinessPicture/"+model.ID);
                    }
                }
                else
                {
                    return Redirect("/Business/BusinessPictureShow/" + business.ID);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }

        /// <summary>
        /// 商户宣传图片删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelBusinessPicture(int id)
        {
            try
            {
                Images image = new Images();
                image = db.Images.Find(id);
                var phicyPath = HostingEnvironment.MapPath(image.Path);
                System.IO.File.Delete(phicyPath);
                db.Images.Remove(image);
                db.SaveChanges();
                return Content("ok");
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("商户宣传图片删除出错", HttpHelper.GetIPAddress()), ex);
                return Content("err");
            }
        }
        #endregion

        #region 商品管理
        /// <summary>
        /// 商品管理页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult ProductManager(int id)
        {
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Bussiness = business;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商品管理页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/ProductManager/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=该商户不存在，请不要不合理操作");
            }
        }
        #endregion

        #region 商品列表
        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult getProduct(int page, int id)
        {
            int index = page * 12;
            List<Product> productlist = db.Products.Where(c => c.BusinessID == id).OrderByDescending(c => c.Time).Skip(index).Take(12).ToList();
            List<vProduct> pro_list = new List<vProduct>();
            foreach (Product item in productlist)
            {
                pro_list.Add(new vProduct(item));
            }
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                if (pro_list.Count == 0)
                {
                    ajaxModel.Data = "";
                    ajaxModel.Statu = "end";
                    ajaxModel.Msg = "数据加载完";
                }
                else
                {
                    ajaxModel.Data = pro_list;
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "加载成功";
                }
            }
            catch (Exception ex)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败";
                log.Error(new LogContent("商品列表生成出错", HttpHelper.GetIPAddress()), ex);
            }
            return Json(ajaxModel);
        }
        #endregion

        #region 增加商品
        /// <summary>
        /// 增加商品界面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult AddProduct(int id)
        {
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Bussiness = business;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("增加商品页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/AddProduct/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=商品不存在，请不要不合理操作");
            }
        }
        /// <summary>
        /// 增加商品操作
        /// </summary>
        /// <param name="model"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Schemas.AccessShowBusiness]
        public ActionResult AddProduct(Product model, int id)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.BusinessID = id;
                    model.Time = DateTime.Now;
                    model.IsPass = false;
                    db.Products.Add(model);
                    db.SaveChanges();
                    return Redirect("/Business/ProductManager/" + id);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("增加商品出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ModelState.AddModelError("", "产品信息填写错误！");
            }
            ViewBag.Bussiness = db.Businesses.Find(id);
            return View();
        }
        #endregion

        #region 展示商品
        /// <summary>
        /// 商品展示页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessBusinessEditProdut]
        public ActionResult ProductShow(int id)
        {
            Product product = db.Products.Find(id);
            if (product != null)
            {
                try
                {
                    List<Images> product_img = db.Images.Where(c => c.TID == id).Where(c => c.ImageType == ImageType.Product).ToList();
                    ViewBag.ProductImg = product_img;
                    ViewBag.Product = new vProduct(product);
                    ViewBag.Bussiness = db.Businesses.Find(ViewBag.Product.BusinessID);
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商品展示页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/ProductShow/"+id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=商品不存在，请不要不合理操作");
            }
        }
        #endregion 

        #region 修改商品
        /// <summary>
        /// 修改商品界面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessBusinessEditProdut]
        public ActionResult ProductEdit(int id)
        {
            Product product = db.Products.Find(id);
            if (product != null)
            {
                try
                {
                    ViewBag.Product = product;
                    ViewBag.Bussiness = db.Businesses.Find(ViewBag.Product.BusinessID);
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改商品信息页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/ProductEdit/" + id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=商品不存在，请不要不合理操作");
            }
        }
        /// <summary>
        /// 修改商品信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ProductEdit(vProduct model, int id)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Product product = db.Products.Find(model.ID);
                    product.ProductName = model.ProductName;
                    product.Description = model.Description;
                    product.Price = model.Price;
                    product.Begin = model.Begin;
                    product.End = model.End;
                    product.BusinessID = model.BusinessID;
                    product.Time = DateTime.Now;
                    product.Integration = model.Integration;
                    product.IsShow = model.IsShow;
                    product.IsPass = false;
                    db.SaveChanges();
                    return Redirect("/Business/ProductManager/" + model.BusinessID);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改商品信息出错", HttpHelper.GetIPAddress()), ex);
                    ModelState.AddModelError("", "产品信息有误，请审核后重新提交");
                }
            }
            else
            {
                ModelState.AddModelError("", "产品信息异常，请刷新页面，重新提交");
            }
            ViewBag.Product = db.Products.Find(model);
            ViewBag.Bussiness = db.Businesses.Find(model.BusinessID);
            return View();
        }
        #endregion

        #region 删除商品
        /// <summary>
        /// 删除商品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        [Schemas.AccessBusinessEditProdut]
        public ActionResult ProductDelete(int id)
        {
            Product product = new Product();
            List<Images> image = new List<Images>();
            product = db.Products.Find(id);
            if (product != null)
            {
                try
                {
                    image = db.Images.Where(c => c.TID == id).ToList();
                    foreach (Images item in image)
                    {
                        var phicyPath = HostingEnvironment.MapPath(item.Path);
                        System.IO.File.Delete(phicyPath);
                        db.Images.Remove(item);
                        db.SaveChanges();
                    }
                    db.SaveChanges();
                    db.Products.Remove(product);
                    db.SaveChanges();
                    return Content("ok");
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("删除商品信息出错", HttpHelper.GetIPAddress()), ex);
                    return Content("err");
                }
            }
            else
            {
                return Content("err");
            }
        }
        #endregion

        #region 商品图片增加
        /// <summary>
        /// 商品图片增加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessBusinessEditProdut]
        public ActionResult AddProductPicture(Product model, HttpPostedFileBase file)
        {
            Product product = db.Products.Find(model.ID);
            if (product != null)
            {
                if (file != null)
                {
                    try
                    {
                        string random = Helpers.DateHelper.GetTimeStamp();
                        Images product_img = new Images();
                        product_img.TID = model.ID;
                        product_img.ImageType = ImageType.Product;
                        product_img.ContentType = file.ContentType;
                        product_img.Time = DateTime.Now;
                        string root = "~/ProductFile/" + product.ProductName + "/";
                        var phicyPath = HostingEnvironment.MapPath(root);
                        Directory.CreateDirectory(phicyPath);
                        file.SaveAs(phicyPath + random + file.FileName);
                        product_img.Path = "/ProductFile/" + product.ProductName + "/" + random + file.FileName;
                        db.Images.Add(product_img);
                        db.SaveChanges();
                        return Redirect("/Business/ProductShow/" + product.ID);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("商品图片增加出错", HttpHelper.GetIPAddress()), ex);
                        return Redirect("/Business/ProductMessage/" + product.BusinessID);
                    }
                }
                else
                {
                    return Redirect("/Business/ProductMessage/" + product.BusinessID);
                }
            }
            else
            {
                return Redirect("/Business/ProductMessage/" + product.BusinessID);
            }
        }
        #endregion

        #region 商品图片删除
        /// <summary>
        /// 商品图片删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        [Schemas.AccessBusinessEditProdut]
        public ActionResult ProductPictureDelete(int id)
        {
            Images image = new Images();
            image = db.Images.Find(id);
            if (image != null)
            {
                try
                {
                    var phicyPath = HostingEnvironment.MapPath(image.Path);
                    System.IO.File.Delete(phicyPath);
                    db.Images.Remove(image);
                    db.SaveChanges();
                    return Content("ok");
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("商品图片删除出错", HttpHelper.GetIPAddress()), ex);
                    return Content("err");
                }
            }
            else
            {
                return Content("err");
            }
        }
        #endregion

        #region 赞
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Up(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    business.Ups = business.Ups + 1;
                    db.SaveChanges();
                    ajaxModel.Data = db.Businesses.Find(id).Ups;
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "赞成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "赞失败！";
                    log.Error(new LogContent("商家赞出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "赞失败！";
            }
            return Json(ajaxModel);
        }
        #endregion

        #region 踩
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Down(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    business.Downs = business.Downs + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Data = db.Businesses.Find(id).Downs;
                    ajaxModel.Msg = "踩成功！";
                }
                catch (Exception ex)
                {
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "赞失败！";
                    log.Error(new LogContent("商家踩出错", HttpHelper.GetIPAddress()), ex);
                }
            }
            else
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "踩失败！";
            }
            return Json(ajaxModel);
        }
        #endregion


        #region 兑换管理
        /// <summary>
        /// 兑换管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowBusiness]
        public ActionResult ExchangeManager(int id, bool? IsExchange, DateTime? Begin, DateTime? End, int page = 1)
        {
            IEnumerable<ExchangeCode> query = db.ExchangeCodes.Where(b => b.Product.BusinessID == id);
            List<vExchangeCode> codes = new List<vExchangeCode>();
            Business business = db.Businesses.Find(id);
            if (business != null)
            {
                try
                {
                    ViewBag.Business = business;
                    if (Begin.HasValue)
                    {
                        query = query.Where(c => c.Time >= Begin);
                    }
                    if (End.HasValue)
                    {
                        query = query.Where(c => c.Time <= End);
                    }
                    if (IsExchange.HasValue)
                    {
                        query = query.Where(c => c.IsExchange == IsExchange);
                    }
                    int totalCount = 0;
                    PagerHelper.DoPage(ref query, page, 20, ref totalCount);
                    foreach (var item in query)
                    {
                        codes.Add(new vExchangeCode(item));
                    }
                    var codesAsIPagedList = new StaticPagedList<vExchangeCode>(codes, page, 20, totalCount);
                    return View(codesAsIPagedList);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("兑换管理页面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/Business/ExchangeManager" + id);
                }
            }
            else
            {
                return Redirect("/Shared/Info?msg=商家不存在，请不要不合理操作");
            }
        }

        /// <summary>
        /// 产品兑换管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult ProductExchange(int id)
        {
            var code = db.ExchangeCodes.Find(id);
            if (code != null)
            {
                try
                {
                    code.IsExchange = true;
                    code.ChangeTime = DateTime.Now;
                    db.SaveChanges();
                    return Content("ok");
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("兑换管理出错", HttpHelper.GetIPAddress()), ex);
                    return Content("err");
                }
            }
            else
            {
                return Content("err");
            }
        }

        #endregion
    }
}